"use client";
import React, { useEffect, useRef } from "react";
import * as cheerio from "cheerio";
import ReactDOMServer from "react-dom/server";

import Page from "../Page";
import { context } from "../context";
import { GetPage } from "./VDom";
import { useDebounceFn } from "ahooks";

export type PageLayout = "top" | "left" | "right";
function Document(props: React.PropsWithChildren) {
  const { children } = props;
  const { onReady, onChange, isNeedPaging, from } = context;

  const ref = useRef<HTMLDivElement>(null);

  const cloneChildren = React.cloneElement(<Page />, {
    children,
  });
  const htmlstring = `<div id='cheerioId'>${ReactDOMServer.renderToString(
    cloneChildren
  )}</div>`;
  const $ = cheerio.load(htmlstring, null, false);

  const { run } = useDebounceFn(
    () => {
      const getWrapper = () => {
        $("link").remove();
        const wraper: any = $("#cheerioId").children().clone();
        return { wraper };
      };
      let pages: any = {};

      const getPage = new GetPage();

      const dealSection = () => {
        const { wraper }: any = getWrapper();
        const dom = wraper[0];
        if (dom) {
          getPage.getVNode(dom);
          const div = document.createElement("div");
          ref.current!.appendChild(div);
          pages = getPage.parseVNode(div);
        }
      };
      ref.current!.innerHTML = "";
      dealSection();
      onReady?.(Object.keys(pages).length);
      let html = "";
      let html2 = "";
      for (const page_num in pages) {
        if (from !== "server") {
          html += `<div style='margin-bottom: 10px'>${pages[page_num].root.outerHTML}</div>`;
        } else {
          html += pages[page_num].root.outerHTML;
        }
        html2 += pages[page_num].root.outerHTML;
      }
      onChange?.(html2);
      ref.current!.innerHTML = html;
    },
    {
      trailing: true,
      wait: 300,
    }
  );
  useEffect(() => {
    if (isNeedPaging) {
      run();
    } else {
      onChange?.(htmlstring);
      onReady?.(1);
    }
  });
  if (isNeedPaging) {
    return (
      <>
        <div ref={ref}></div>
      </>
    );
  } else {
    return cloneChildren;
  }
}

// 获取根节点

// 开始遍历
export default Document;
